<?php

namespace App\Http\Controllers\Admin;

use App\Models\Teacher;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;

class TeacherController extends CommonController
{

    public function index()
    {
        $data=Teacher::orderBy('id','desc')->withTrashed()->paginate($this->page);
        return view('admin.teacher.index',compact('data'));
    }

    public function create()
    {
        return view('admin.teacher.create');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \Illuminate\Validation\ValidationException
     * 添加处理
     */

    public function store(Request $request)
    {
        $post=$this->validate($request,[
            'username'=>'required|unique:admins,username',
            'truename'=>'required',
            'password'=>'required|confirmed',
            'phone' =>'required|phone',
            'email'=>'required|email',
        ]);
        $model=Teacher::create($post);
        $password=$post['password'];
        //发送通知邮件
        \Mail::send('email.adminUser',compact('model','password'),function (Message $message) use ($model) {
            $message->to($model->email);
            //主题名
            $message->subject('学校管理后台账号开通通知');
        });
        //日志
        return redirect(route('admin.teacher.index'))->with(['error'=>'添加用户'.$post['username'].'成功']);

    }

  /**
   * 显示
   */
    public function show(Teacher $teacher)
    {
        //
    }

    /**
     * @param Teacher $teacher
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 修改视图
     */
    public function edit(Teacher $teacher)
    {
        return view('admin.teacher.edit',compact('teacher'));
    }

    public function update(Request $request, Teacher $teacher)
    {
        $post=$this->validate($request,[
            'username'=>'required',
            'truename'=>'required',
            'phone' =>'required|phone',
            'email'=>'required|email',
        ]);
        try {
            $teacher->update($post);
            //发送邮件
            //写入日志
            return redirect(route('admin.teacher.index'))->with(['error'=>'修改老师资料成功']);
        }catch (\Illuminate\Database\QueryException $queryException){
            //写入日志
            return redirect(route('admin.admin.edit',$teacher))->with(['error'=>'修改失败，可能账号已经存在']);
        }

    }


    public function destroy(Teacher $teacher)
    {
        $teacher->delete();
        return ['status'=>0,'msg'=>'删除成功'];
    }
    public function restore(int $id)
    {
        Teacher::withTrashed()->find($id)->restore();
        return redirect(route('admin.teacher.index'))->with(['error'=>'恢复用户成功']);
    }
}
